package com.example.spring.jpa.specification;

import com.example.spring.jpa.ast.PriorityOperation;

import javax.persistence.criteria.*;
import java.text.ParseException;

/**
 * @author: orange
 * @create: 2023-07-24 19:38
 * @description:
 */
public class StringGenerate extends GlobalPredicate {

    @Override
    public Expression<String> getExpression(GenerateApplicationContext context) {
        if (context.getPath() != null) {
            return context.getRoot().as(String.class);
        }
        return context.getRoot().get(context.getLeft()).as(String.class);
    }

    @Override
    public Predicate doGenerate(GenerateApplicationContext context) throws ParseException {
        if (PriorityOperation.NotEquals$1.getOperation().equals(context.getOperation())
                || PriorityOperation.NotEquals$2.getOperation().equals(context.getOperation())) {
            return context.getBuilder().notEqual(getExpression(context), context.getRight());
        } else if (PriorityOperation.SaferEquals.getOperation().equals(context.getOperation())) {
            return context.getBuilder().equal(getExpression(context), context.getRight());
        } else if (PriorityOperation.GTE.getOperation().equals(context.getOperation())) {
            return context.getBuilder().greaterThanOrEqualTo(getExpression(context), context.getRight());
        } else if (PriorityOperation.LTE.getOperation().equals(context.getOperation())) {
            return context.getBuilder().lessThanOrEqualTo(getExpression(context), context.getRight());
        } else if (PriorityOperation.Equals.getOperation().equals(context.getOperation())) {
            return context.getBuilder().equal(getExpression(context), context.getRight());
        } else if (PriorityOperation.LIKE.getOperation().equals(context.getOperation())) {
            return context.getBuilder().like(getExpression(context), context.getRight());
        } else if (PriorityOperation.NotLIKE.getOperation().equals(context.getOperation())) {
            return context.getBuilder().notLike(getExpression(context), context.getRight());
        }
        throw new RuntimeException(String.format("String类型不能使用%s运算符！", context.getOperation()));
    }
}
